import { ReactNode, createContext, useState } from 'react'
import { delComponentApi, overridComponent, saveComponent } from '../controllers/API'
import { captureAndAlertRequestErrorHoc } from '../controllers/request'
import { User } from '../types/api/user'

import { getPermissionsApi } from '@/controllers/API/common'
// import { backendPermissionList } from '@/permissions/constants'
import { handlePermissionToFrontend } from '@/permissions/utils'
import { useFuncsStore } from '@/store/funcStore'

type userContextType = {
  user: User // {} loading null login
  setUser: (newState: User) => void
  savedComponents: any
  addSavedComponent: (newCom: any, overrid: boolean, rename?: boolean) => Promise<any>
  checkComponentsName: (name: string) => boolean
  delComponent: (name: string) => void
  setUserInfo: (userInfo: any) => Promise<any>
}

// const userInfoLocalStr = localStorage.getItem('UUR_INFO')
const initialValue = {
  user: {}, // userInfoLocalStr ? JSON.parse(atob(userInfoLocalStr)) : null,
  setUser: () => {},
  savedComponents: [],
  addSavedComponent: () => null,
  checkComponentsName: () => false,
  delComponent: () => {},
  setUserInfo: () => null
}

export const userContext = createContext<userContextType>(initialValue)

export function UserProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User>(initialValue.user)
  const [savedComponents, setSavedComponents] = useState([])

  /**
   * 权限信息
   */
  const { setNeedFuncAuth, setFuncCodes } = useFuncsStore()

  const loadComponents = async () => {
    // const res = await getComponents()
    // setSavedComponents(res)
    // todo 数据未使用，后期存在使用时打开上面的接口数据加载
    console.log(
      '>>>>>>>> 目前页面未使用到/api/v1/component结果，启用该接口时需先讨论优化方案，2024830测试该接口dev环境耗时1分钟，返回数据量119M'
    )
    setSavedComponents([])
  }

  // 重名校验
  const checkComponentsName = (name: string) => {
    return savedComponents.some(item => item.name === name)
  }

  const addSavedComponent = (component: any, overrid: boolean, rename: boolean = true) => {
    // return delComponent(component.type)
    const nodeName = component.node.display_name
    const newNode = {
      ...component,
      node: { ...component.node, official: false }
    }

    const data = {
      name: nodeName,
      data: newNode,
      description: ''
    }
    // 覆盖
    if (overrid) {
      return captureAndAlertRequestErrorHoc(overridComponent(data)).then(res => {
        setSavedComponents(comps => comps.map(comp => (comp.name === data.name ? data : comp)))
      })
    } else {
      // 重命名
      if (rename) {
        const regex = /\((\d+)\)$/
        do {
          const match = data.name.match(regex)
          if (match) {
            // 如果找到匹配项，将数字提取出来，转换成数字类型，并加1
            const num = parseInt(match[1], 10) + 1
            data.name = data.name.replace(regex, `(${num})`)
          } else {
            data.name += '(1)'
          }
        } while (savedComponents.some(item => item.name === data.name))
      }
      return captureAndAlertRequestErrorHoc(saveComponent(data)).then(sucess => {
        sucess && setSavedComponents([...savedComponents, data])
      })
    }
  }

  // del
  const delComponent = name => {
    delComponentApi(name).then(res => {
      setSavedComponents(comps => comps.filter(item => item.name !== name))
    })
  }

  const setUserInfo = (userInfo: any) => {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    setUser({
      user_id: userInfo.user_id,
      user_name: userInfo.user_name,
      role: userInfo.roles || [],
      create_time: userInfo.create_time,
      access_token: userInfo.access_token,
      update_time: userInfo.update_time,
      enterprise_id: userInfo.enterprise_id
    })

    const needAuth = !userInfo?.roles?.includes('admin')
    // const needAuth = true

    return new Promise<void>((resolve, reject) => {
      if (needAuth) {
        setNeedFuncAuth(true)
        setUserFuncList()
          .then(() => {
            completeLoginSetup(userInfo)
            resolve()
          })
          .catch(error => {
            console.error('设置角色和权限失败', error)
            reject(error)
          })
      } else {
        completeLoginSetup(userInfo)
        resolve()
      }
    })
  }

  // 获取用户角色权限
  const setUserFuncList = () => {
    console.log('>>>>>>非root用户限制功能权限')
    return getPermissionsApi()
      .then(res => {
        console.log('getPermissionsApi', res)
        const permissionList = handlePermissionToFrontend(res || [])
        setFuncCodes(permissionList)
        // setFuncCodes(handlePermissionToFrontend(backendPermissionList))
      })
      .catch(error => {
        console.error('error', error)
        throw error
      })
  }

  // 完成登录状态设置
  const completeLoginSetup = (userInfo: any) => {
    localStorage.setItem('isLogin', '1')
    // UUR_INFO存储用户信息，暂时先存储id，后期扩展时需考虑缓存用户关键信息
    localStorage.setItem('UUR_INFO', String(userInfo.user_id))
    if (userInfo.user_id) loadComponents()
  }

  return (
    <userContext.Provider
      value={{
        user,
        setUser,
        savedComponents,
        checkComponentsName,
        delComponent,
        addSavedComponent,
        setUserInfo
      }}
    >
      {children}
    </userContext.Provider>
  )
}
